<template>
  <!-- :bodyStyle="{ height: '150px' }" -->
  <a-modal
    :title="title"
    width="25%"
    :visible="visible"
    :confirmLoading="loading"
    :footer="null"
    @cancel="
      () => {
        this.visible = false
      }
    "
  >
    <template>
      <a-spin :spinning="loading">
        <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
          <a-form-model-item label="导入类型" prop="DrModel" v-if="showSelect">
            <a-select style="width: 100%" v-model="DrModel">
              <a-select-option value="Import">设计清单</a-select-option>
              <a-select-option value="ImportOrder">补加单</a-select-option>
              <a-select-option value="ChangeOrder">变更单</a-select-option>
              <a-select-option value="MaterialTable">料台清单</a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item label="项目:" prop="ProjectId" v-if="showSelect">
            <ProjectSelect v-model="entity.ProjectId" @select="project"></ProjectSelect>
          </a-form-model-item>
          <a-form-model-item label="楼号：" prop="BuildingNumberID" v-if="showSelect">
            <a-select style="width: 100%" @change="changelohao" v-model="entity.BuildingNumberID" allowClear>
              <a-select-option v-for="(item, index) in lohao" :key="index" :value="item.Id">
                {{ item.Buildingnumber }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item v-if="showTimer" label="日期选择" prop="time">
            <a-range-picker :value="time" @change="ontimeChange" v-model="entity.time" />
          </a-form-model-item>
        </a-form-model>
      </a-spin>

      <!-- <a-row>
        <a-col v-if="showSelect" :span="12">
          导入类型：<a-select style="width: 100%" v-model="DrModel">
            <a-select-option value="Import">设计清单</a-select-option>
            <a-select-option value="ImportOrder">补加单</a-select-option>
            <a-select-option value="ChangeOrder">变更单</a-select-option>
          </a-select>
        </a-col>
      </a-row>
      <a-row :gutter="20" v-show="templet == '/PB/PB_DesignList/ExportToExcel'">
        <a-col :span="12">
          项目：
          <ProjectSelect v-model="entity.ProjectId" @select="project"></ProjectSelect>
        </a-col>
        <a-col :span="12">
          楼号：
          <a-select style="width: 100%" @change="changelohao" v-model="entity.BuildingNumberID" allowClear>
            <a-select-option v-for="(item, index) in lohao" :key="index" :value="item.Id">
              {{ item.Buildingnumber }}
            </a-select-option>
          </a-select>
        </a-col>
      </a-row> -->

      <a-row :gutter="10" style="margin-top: 30px">
        <a-col
          :span="templet != '/PB/PB_DesignList/ExportToExcel' ? 12 : 24"
          :style="templet != '/PB/PB_DesignList/ExportToExcel' ? '' : 'text-align: center;'"
        >
          <!-- :md="14" :sm="24" -->
          <a-upload
            name="file"
            :beforeUpload="beforeUpload"
            :multiple="true"
            :action="action"
            :headers="headers"
            @change="handleChange"
          >
            <a-button type="primary"> <a-icon type="upload" /> 上传数据 </a-button>
          </a-upload>
        </a-col>

        <a-col :span="12" style="text-align: right" v-show="templet != '/PB/PB_DesignList/ExportToExcel'">
          <a-button
            @click="
              () => {
                this.visible = false
              }
            "
            ><a-icon type="download" />
            <!-- <a :href=" $rootUrl+templet">下载模板表</a> -->
            <a @click="LoadClick($rootUrl + templet)">下载模板表</a>
            <!--  -->
          </a-button>
        </a-col>
      </a-row>
    </template>
  </a-modal>
</template>

<script>
import Token from '../../utils/cache/TokenCache'
import { download } from '@/components/download'
// import ProjectSelect from '@/components/PB/ProjectSelect'
export default {
  components: {
    Token,
    // ProjectSelect,
  },
  props: {
    parentObj: Object,
    // rootUrl:$rootUrl,
    leading: { type: String, required: false },
    templet: { type: String, required: false },
  },
  data() {
    return {
      DrModel: '',
      showSelect: false,
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
      },
      lohao: [],
      name: '',
      visible: false,
      loading: false,
      rules: {
        DrModel: [{ required: true, validator: this.validatePass1, trigger: 'change' }],
        ProjectId: [{ required: true, message: '请选择项目', trigger: 'change' }],
        BuildingNumberID: [{ required: true, message: '请选择楼号', trigger: 'change' }],
        time: [{ required: true, message: '请选择日期', trigger: 'change' }],
      },
      title: '',
      headers: {
        authorization: 'Bearer ' + Token.getToken(),
      },
      entity: {
        ProjectId: '',
      },
      showTimer: false,
      time: null,
    }
  },
  computed: {
    action() {
      if (this.showSelect && this.DrModel) {
        if (this.DrModel == 'Import')
          return `${this.$rootUrl}/PB/PB_DesignList/Import?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${this.entity.BuildingNumberID}`
        else if (this.DrModel == 'ImportOrder')
          return `${this.$rootUrl}/PB/PB_DesignList/ImportOrder?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${this.entity.BuildingNumberID}`
        else if (this.DrModel == 'ChangeOrder')
          return `${this.$rootUrl}/PB/PB_DesignList/ImportChangeOrder?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${this.entity.BuildingNumberID}`
        else if (this.DrModel == 'MaterialTable')
          return `${this.$rootUrl}/PB/PB_DesignList/ImportMaterialTable?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${this.entity.BuildingNumberID}`
      } else {
        return this.leading == '/PB/PB_DesignList/Import'
          ? `${this.$rootUrl}/PB/PB_DesignList/Import?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${this.entity.BuildingNumberID}`
          : this.$rootUrl + this.leading
      }
    },
  },
  methods: {
    ontimeChange(date, a) {
      this.StartDate = a[0]
      this.EndDate = a[1]
    },
    validatePass1(rule, value, callback) {
      if (this.DrModel) callback()
      else callback(new Error('请选择导入类型'))
    },
    beforeUpload(file, fileList) {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate((valid) => {
          if (!valid) {
            reject()
          } else {
            if (this.showTimer) {
              if (this.leading.split('?').length >= 2) {
                this.leading = this.leading.split('?')[0] + '?StartDate=' + this.StartDate + '&EndDate=' + this.EndDate
              } else {
                this.leading = this.leading + '?StartDate=' + this.StartDate + '&EndDate=' + this.EndDate
              }
            }
            resolve()
          }
        })
      })
    },
    changelohao(val) {
      //楼号
      console.log(val)
      this.$set(this.entity, 'BuildingNumberID', val)
      console.log(this.entity)
    },
    project(row) {
      this.lohao = []
      delete this.entity.BuildingNumberID
      this.Getlohao(row.Id)
      console.log(row.Id)
    },
    Getlohao(id) {
      this.$http.post('/PB/PB_Buildingnumber/GetDataLists?ProjectId=' + id).then((res) => {
        console.log(res)
        this.lohao = res.Data
      })
    },
    init() {
      this.visible = true
    },
    openForm(id, title, name, DrModel) {
      // console.log(name)
      this.init()
      this.title = title
      this.name = name
      this.showSelect = false
      this.showTimer = false
      this.time = null
      if (DrModel) this.showSelect = true
      else if (DrModel === false) this.showTimer = true
    },
    handleChange(info) {
      console.log(info)
      if (this.templet == '/PB/PB_DesignList/ExportToExcel') {
        // var str = `/PB/PB_DesignList/ExportToExcel?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${this.entity.BuildingNumberID}`
        // console.log(str)
        // this.templet = str
      }
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.Success === false) {
          let str = info.file.response.Msg
          let str1 = str.split(',').join('\n')
          this.$message.error(`${info.file.name}文件,${str1},请检查文件内容！ `)
          this.exportRaw('错误内容.txt', str1)
        } else {
          this.$message.success(`${info.file.name}  文件上传成功！`)
        }
        this.visible = false
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败！`)
      }
    },
    LoadClick(url) {
      console.log(this.name)
      download(url, this.name)
    },
    fakeClick(obj) {
      var ev = document.createEvent('MouseEvents')
      ev.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
      obj.dispatchEvent(ev)
    },
    exportRaw(name, data) {
      var urlObject = window.URL || window.webkitURL || window
      var export_blob = new Blob([data])
      var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a')
      save_link.href = urlObject.createObjectURL(export_blob)
      save_link.download = name
      this.fakeClick(save_link)
    },
  },
  watch: {
    leading(a) {
      console.log(a)
      // if (a == '/PB/PB_DesignList/Import') {
      //   this.leading = `/PB/PB_DesignList/Import?ProjectId=${this.entity.ProjectId}&BuildingNumberID=${this.entity.BuildingNumberID}`
      // }
    },
    'entity.ProjectId': {
      handler(newVal, oldVal) {
        if (newVal && !oldVal) {
          this.$refs['form'].fields.forEach((filed) => {
            if (filed.prop == 'ProjectId') {
              filed.clearValidate()
            }
          })
        }
      },
      deep: true,
      immediate: true,
    },
  },
}
</script>
